package com.six.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.six.bean.Category;
import com.six.bean.Tadmin;
import com.six.service.CategoryService;
import com.six.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("category")
@CrossOrigin
public class CategoryController {

    @Autowired
    CategoryService categoryService;


    @GetMapping("list")
    public Result getList() {
        List<Category> list = categoryService.list();
        return Result.success(list);
    }


    @PostMapping
    public Result add(@RequestBody Category category) {
        categoryService.save(category);
        Category category1 = categoryService.getById(category.getCateid());
        return Result.success("保存成功", category1);
    }


    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") int cateid) {
        boolean b = categoryService.removeById(cateid);
        if (b) {
            return Result.success("删除成功");
        } else {
            return Result.fail(201, "删除失败");
        }
    }

    /**
     * 修改分类信息
     * @param category 前端传入的包含修改后分类信息的对象
     * @return 包含修改后分类数据及操作结果提示的 Result 对象
     */
    @PutMapping
    public Result edit(@RequestBody Category category) {
        boolean b = categoryService.saveOrUpdate(category);
        Category category1 = categoryService.getById(category.getCateid());
        if (b) {
            return Result.success("保存成功", category1);
        } else {
            return Result.fail(201, "修改失败");
        }
    }
    @GetMapping("page")
    public Result getPage(Page page, @RequestParam("searchtext") String searchtext) {
        System.out.println(searchtext);
        IPage<Tadmin> result = null;
        if (searchtext == null || searchtext.trim().isEmpty()) {
            result = categoryService.page(page);
        } else {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.like("catename", searchtext);

            result = categoryService.page(page, wrapper);
        }

        return Result.success(result);
    }
}